﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Telerik.WinControls.UI;
using log4net;
using System.Text.RegularExpressions;
using Telerik.WinControls.Data;
using System.Collections;

namespace QuanLyNhaSach
{
    public partial class frmHoaDonBanSi : Form
    {
        #region bien
        //Tao Parttern Seleton
        static frmHoaDonBanSi doituong = null;
        sv_QuanLyNhaSach.AdapterClient service = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;
        public string manv_frmhdbs = frmDangNhap.maNV_FromDangNhap;
        string mamh, tenmh, soluong, dongia, thanhtien;
        double tienDaDua = 0;
        double tienConLai = 0;
        float chietkhau;
        double tienthue = 0;
        int stt = 0;
        int vitri = 0;
        double tongtien = 0;
        double tongtienhang = 0;
        public string manv = frmDangNhap.maNV_FromDangNhap;
        ArrayList Test_DMKho;
        ArrayList Test_DMKH;
        KiemTraBatLoi batloi = new KiemTraBatLoi();
        #endregion

        public static frmHoaDonBanSi TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmHoaDonBanSi();
            return doituong;
        }

        public frmHoaDonBanSi()
        {
            InitializeComponent();
        }

        #region "Ham chuyen so thanh chu"
        private static string Chu(string gNumber)
        {
            string result = "";
            switch (gNumber)
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        private static string Donvi(string so)
        {
            string Kdonvi = "";

            if (so.Equals("1"))
                Kdonvi = "";
            if (so.Equals("2"))
                Kdonvi = "nghìn";
            if (so.Equals("3"))
                Kdonvi = "triệu";
            if (so.Equals("4"))
                Kdonvi = "tỷ";
            if (so.Equals("5"))
                Kdonvi = "nghìn tỷ";
            if (so.Equals("6"))
                Kdonvi = "triệu tỷ";
            if (so.Equals("7"))
                Kdonvi = "tỷ tỷ";

            return Kdonvi;
        }
        private static string Tach(string tach3)
        {
            string Ktach = "";
            if (tach3.Equals("000"))
                return "";
            if (tach3.Length == 3)
            {
                string tr = tach3.Trim().Substring(0, 1).ToString().Trim();
                string ch = tach3.Trim().Substring(1, 1).ToString().Trim();
                string dv = tach3.Trim().Substring(2, 1).ToString().Trim();
                if (tr.Equals("0") && ch.Equals("0"))
                    Ktach = " không trăm lẻ " + Chu(dv.ToString().Trim()) + " ";
                if (!tr.Equals("0") && ch.Equals("0") && dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm ";
                if (!tr.Equals("0") && ch.Equals("0") && !dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm lẻ " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (tr.Equals("0") && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm mười " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("0"))
                    Ktach = " không trăm mười ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("5"))
                    Ktach = " không trăm mười lăm ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười " + Chu(dv.Trim()).Trim() + " ";

                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười lăm ";

            }


            return Ktach;

        }
        public static string So_chu(double gNum)
        {
            if (gNum == 0)
                return "Không đồng";

            string lso_chu = "";
            string tach_mod = "";
            string tach_conlai = "";
            double Num = Math.Round(gNum, 0);
            string gN = Convert.ToString(Num);
            int m = Convert.ToInt32(gN.Length / 3);
            int mod = gN.Length - m * 3;
            string dau = "[+]";

            // Dau [+ , - ]
            if (gNum < 0)
                dau = "[-]";
            dau = "";

            // Tach hang lon nhat
            if (mod.Equals(1))
                tach_mod = "00" + Convert.ToString(Num.ToString().Trim().Substring(0, 1)).Trim();
            if (mod.Equals(2))
                tach_mod = "0" + Convert.ToString(Num.ToString().Trim().Substring(0, 2)).Trim();
            if (mod.Equals(0))
                tach_mod = "000";
            // Tach hang con lai sau mod :
            if (Num.ToString().Length > 2)
                tach_conlai = Convert.ToString(Num.ToString().Trim().Substring(mod, Num.ToString().Length - mod)).Trim();

            ///don vi hang mod 
            int im = m + 1;
            if (mod > 0)
                lso_chu = Tach(tach_mod).ToString().Trim() + " " + Donvi(im.ToString().Trim());
            /// Tach 3 trong tach_conlai

            int i = m;
            int _m = m;
            int j = 1;
            string tach3 = "";
            string tach3_ = "";

            while (i > 0)
            {
                tach3 = tach_conlai.Trim().Substring(0, 3).Trim();
                tach3_ = tach3;
                lso_chu = lso_chu.Trim() + " " + Tach(tach3.Trim()).Trim();
                m = _m + 1 - j;
                if (!tach3_.Equals("000"))
                    lso_chu = lso_chu.Trim() + " " + Donvi(m.ToString().Trim()).Trim();
                tach_conlai = tach_conlai.Trim().Substring(3, tach_conlai.Trim().Length - 3);

                i = i - 1;
                j = j + 1;
            }
            if (lso_chu.Trim().Substring(0, 1).Equals("k"))
                lso_chu = lso_chu.Trim().Substring(10, lso_chu.Trim().Length - 10).Trim();
            if (lso_chu.Trim().Substring(0, 1).Equals("l"))
                lso_chu = lso_chu.Trim().Substring(2, lso_chu.Trim().Length - 2).Trim();
            if (lso_chu.Trim().Length > 0)
                lso_chu = dau.Trim() + " " + lso_chu.Trim().Substring(0, 1).Trim().ToUpper() + lso_chu.Trim().Substring(1, lso_chu.Trim().Length - 1).Trim() + " đồng chẵn.";

            return lso_chu.ToString().Trim();

        }
        #endregion

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        #region Load Form
        private void frmHoaDonBanSi_Load(object sender, EventArgs e)
        {
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            //Su kien Enter
            this.KeyDown += new KeyEventHandler(frmHoaDonBanSi_KeyDown);
            cmbkhachhang.KeyDown += new KeyEventHandler(cmbkhachhang_KeyDown);
            cmbmahang.KeyDown += new KeyEventHandler(cmbmahang_KeyDown);
            txtsoluong.KeyDown+=new KeyEventHandler(txtsoluong_KeyDown);
            bt_chuyenxuong.KeyDown += new KeyEventHandler(bt_chuyenxuong_KeyDown);
            txtdathanhtoan.KeyDown += new KeyEventHandler(txtdathanhtoan_KeyDown);
            //--------------------
            try
            {
                //set ngay thang hien tai
                dtpngaylaphd.Value = DateTime.Now;

                //focus vao so thu tu
                txtsochungtu.Focus();
                //set ten nhan vien
                DataSet ds_TenNhanVien = new DataSet();
                ds_TenNhanVien.ReadXml(new StringReader(service.selectqueryByText("select HoTenNV from NhanVien where MaNV = '" + frmDangNhap.maNV_FromDangNhap + "'")));
                if (ds_TenNhanVien.Tables.Count > 0)
                {
                    txt_HoTenNV.Text = ds_TenNhanVien.Tables[0].Rows[0][0].ToString();
                }
                //Load
                LoadDuLieu();
                //Load ds Phieu DH NCC
                Load_DSPhieuDatNCCChuaGiao();

            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        void txtdathanhtoan_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                btluu.Focus();
            }
        }

        void frmHoaDonBanSi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F2)
            {
                txtdathanhtoan.Focus();
                txtdathanhtoan.SelectionStart = txtdathanhtoan.Text.Length;
            }
            if (e.KeyData== Keys.F3)
            {
                Luu();
            }
        }

        void bt_chuyenxuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                cmbmahang.Focus();
            }
        }

        void txtsoluong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                bt_chuyenxuong.Focus();
            }
        }

        void cmbmahang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                txtsoluong.Focus();
                txtsoluong.SelectionStart = txtsoluong.Text.Length;
            }
        }

        void cmbkhachhang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                cmbmahang.Focus();
            }
        }
        #endregion

        #region Các hàm SelectedIndexChanged
        private void cmbkhachhang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbkhachhang.Text == "")
                {
                    txtdiachi.Text = "";
                }
                else
                {
                    txtdiachi.Text = cmbkhachhang.EditorControl.Rows[cmbkhachhang.SelectedIndex].Cells["DiaChiKH"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }
        private void cmbmahang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbmahang.Text == "")
                {
                    txtmamh.Text = "";
                    txtdongia.Text = "0";
                    txtsoluong.Text = "1";
                    txtthanhtien.Text = "0";
                    cmbdvt.Text = "";
                    txtkm.Text = "0";
                }
                else
                {
                    txtmamh.Text = cmbmahang.SelectedValue.ToString().Trim();
                    txtdongia.Text = double.Parse(cmbmahang.EditorControl.Rows[cmbmahang.SelectedIndex].Cells["dongiasi"].Value.ToString()).ToString("#,##0");
                    cmbdvt.Text = cmbmahang.EditorControl.Rows[cmbmahang.SelectedIndex].Cells["dvt"].Value.ToString().Trim();

                    //DataSet ds = new DataSet();
                    //ds.ReadXml(new StringReader(service.selectqueryByText("select MaMH, DonGiaSi,dvt from MatHang where MaMH = '" + cmbmahang.SelectedValue.ToString().Trim() + "'")));
                    //if (ds.Tables.Count > 0)
                    //{
                    //    double dongiaMatHang = double.Parse(ds.Tables[0].Rows[0]["DonGiaSi"].ToString());
                    //    if (cmbmahang.SelectedIndex != -1)
                    //    {
                    //        txtmamh.Text = ds.Tables[0].Rows[0]["MaMH"].ToString();
                    //        txtdongia.Text = dongiaMatHang.ToString("#,##0");
                    //        cmbdvt.Text = ds.Tables[0].Rows[0]["DVT"].ToString();
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }
        private void mcb_phieukhdathang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //Chinh do dai cua cac cot trong multicombobox
                if (mcb_phieukhdathang.Text.Trim() == "")
                {
                    //Xoa het thong tin binding
                    gv_ctbansi.DataSource = null;
                    cmbkhohang.Text = "";
                    cmbkhachhang.Text = "";
                    txtghichu.Text = "";
                    txtkhtamung.Text = "0";
                    txttongthanhtien.Text = "0";
                    txttongthanhtientinhthue.Text = "0";
                }
                else
                {
                    for (int i = 0; i < mcb_phieukhdathang.EditorControl.Rows.Count; i++)
                    {
                        if (cmbkhachhang.EditorControl.Rows[i].Cells["MaKH"].Value.ToString().Trim() == mcb_phieukhdathang.EditorControl.Rows[mcb_phieukhdathang.SelectedIndex].Cells["MaKH"].Value.ToString().Trim())
                            cmbkhachhang.EditorControl.Rows[i].IsCurrent = true;
                        if (cmbkhohang.EditorControl.Rows[i].Cells["MaKho"].Value.ToString().Trim() == mcb_phieukhdathang.EditorControl.Rows[mcb_phieukhdathang.SelectedIndex].Cells["MaKho"].Value.ToString().Trim())
                            cmbkhohang.EditorControl.Rows[i].IsCurrent = true;
                    }
                    txtkhtamung.Text = double.Parse(mcb_phieukhdathang.EditorControl.Rows[mcb_phieukhdathang.SelectedIndex].Cells["TamUng"].Value.ToString()).ToString("#,##0");
                    // Load dữ liệu các mặt hàng chưa gia lên GidView
                    string sql = "Select ct.MaMH,TenMH,SoLuong,DonGia,ChietKhau,ThanhTien "
                                 + "from PhieuKHDatHang hd,CTKHDatHang ct,MatHang mh "
                                 + "where hd.MaKHDH = ct.MaKHDH and mh.MaMH = ct.MaMH and DaGiao = 'false' and hd.MaKHDH = '" + mcb_phieukhdathang.SelectedValue.ToString().Trim() + "' "
                                 + "group by ct.MaMH,TenMH,SoLuong,DonGia,ChietKhau,ThanhTien";
                    DataSet ds = new DataSet();
                    ds.ReadXml(new StringReader(service.selectqueryByText(sql)));
                    if (ds.Tables.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ds.Tables[0].Rows[i]["DonGia"] = double.Parse(ds.Tables[0].Rows[i]["DonGia"].ToString()).ToString("#,##0");
                            ds.Tables[0].Rows[i]["ChietKhau"] = float.Parse(ds.Tables[0].Rows[i]["ChietKhau"].ToString()).ToString("0.0");
                            ds.Tables[0].Rows[i]["ThanhTien"] = (double.Parse(ds.Tables[0].Rows[i]["DonGia"].ToString()) * double.Parse(ds.Tables[0].Rows[i]["SoLuong"].ToString()) - double.Parse(ds.Tables[0].Rows[i]["DonGia"].ToString()) * double.Parse(ds.Tables[0].Rows[i]["SoLuong"].ToString()) * float.Parse(ds.Tables[0].Rows[i]["ChietKhau"].ToString()) / 100).ToString("#,##0");
                        }
                        gv_ctbansi.DataSource = ds.Tables[0];
                    }
                    //Tao them nut xoa mat hang
                    if (gv_ctbansi.Columns.GetColumnByFieldName("xoa").Length == 0)
                    {
                        GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                        btnColumn.FieldName = "xoa";
                        btnColumn.Name = "xoa";
                        btnColumn.UseDefaultText = true;
                        btnColumn.DefaultText = "Xóa";
                        gv_ctbansi.Columns.Insert(gv_ctbansi.Columns.Count, btnColumn);
                    }
                    //Tao STT trong Gridview va cap nhat lai Tong Tien hang
                    if (gv_ctbansi.Rows.Count > 0)
                    {
                        tongtienhang = 0;
                        tongtien = 0;
                        for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                        {
                            gv_ctbansi.Rows[i].Cells["STT"].Value = i + 1;
                            //Tinh Tong Tien
                            tongtienhang += double.Parse(gv_ctbansi.Rows[i].Cells["ThanhTien"].Value.ToString());
                        }
                        txttongthanhtien.Text = tongtienhang.ToString("#,##0");
                        tongtien = tongtienhang + double.Parse(txttienthue.Text) - double.Parse(txtkhtamung.Text);
                        txttongthanhtientinhthue.Text = tongtien.ToString("#,##0");
                        txttienchu.Text = So_chu(tongtien);
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        #endregion        

        private void btluu_Click(object sender, EventArgs e)
        {
            Luu();
        }

        private void Luu()
        {
            errorProvider1.Clear();
            errorProvider1.RightToLeft = false;
            lbl_Thongbao.Text = "Thông báo!";
            if (txtsochungtu.Text.Trim() == "")
            {
                errorProvider1.SetError(txtsochungtu, "Vui lòng nhập thông tin chứng từ.");
                txtsochungtu.Focus();
                return;
            }
            if (cmbkhohang.Text.Trim() == "")
            {
                errorProvider1.SetError(cmbkhohang, "Chưa chọn kho hàng");
                cmbkhohang.Focus();
                return;
            }
            if (Test_DMKho.Contains(cmbkhohang.Text.Trim()) == false)
            {
                errorProvider1.SetError(cmbkhohang, "Nhập sai thông tin Kho Hàng.");
                cmbkhohang.Focus();
                return;
            }
            if (cmbkhachhang.Text.Trim() == "")
            {
                errorProvider1.SetError(cmbkhachhang, "Chưa chọn Khach hang");
                cmbkhachhang.Focus();
                return;
            }
            if (Test_DMKH.Contains(cmbkhachhang.Text.Trim()) == false)
            {
                errorProvider1.SetError(cmbkhachhang, "Nhập sai thông tin Kho Hàng.");
                cmbkhachhang.Focus();
                return;
            }
            if (gv_ctbansi.Rows.Count == 0)
            {
                lbl_Thongbao.Text = "Chưa có dữ liệu chi tiết mua hàng";
                errorProvider1.SetError(lbl_Thongbao, "Vui lòng nhập thông tin chi tiết mặt hàng");
                return;
            }
            else
            {
                #region "Kiem tra thông tin từng cell tren lưới"
                for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                {
                    try
                    {
                        if (Regex.IsMatch(gv_ctbansi.Rows[i].Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_ctbansi.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                        {
                            lbl_Thongbao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_Thongbao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        if (Regex.IsMatch(gv_ctbansi.Rows[i].Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,9}$") == false)
                        {
                            lbl_Thongbao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_Thongbao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        if (Regex.IsMatch(gv_ctbansi.Rows[i].Cells["Chietkhau"].Value.ToString().Trim(), @"^\d{1,2}$") == false || int.Parse(gv_ctbansi.CurrentRow.Cells["ChietKhau"].Value.ToString()) > 50)
                        {
                            lbl_Thongbao.Text = "Số chiết khấu từ 0 - 50 %";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_Thongbao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        lbl_Thongbao.Text = "Thông báo!";
                        errorProvider1.RightToLeft = true;
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Error: " + ex.Message);
                    }
                }
                #endregion
            }
            try
            {
                //Khai bao thong tin ben luu vao CSDL
                string mahd = xulyma();
                string makho = cmbkhohang.SelectedValue.ToString();
                string makh = cmbkhachhang.SelectedValue.ToString();
                string sochungtu = txtsochungtu.Text;
                DateTime ngaylap = dtpngaylaphd.Value;
                float mucthue = float.Parse(txtvat.Text) / 100;
                string ghichu = txtghichu.Text;
                string diachi = txtdiachi.Text;
                double tongtientinhthue = tongtien;
                double dadua = tienDaDua;
                double conlai = tienConLai;
                DateTime hanthanhtoan = DateTime.Now;
                string nguoinhan = txtnguoinhan.Text;
                if (!service.InsertHDBS(mahd, makho.Trim(), makh, manv, nguoinhan, ngaylap, sochungtu, ghichu, diachi, mucthue, tongtientinhthue, dadua, conlai, hanthanhtoan))
                {
                    MessageBox.Show("Lưu thất bại!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                //Duyet qua Gridview de them vao bang Chi Tiet hoá đơn ban si
                for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                {
                    string mamh = gv_ctbansi.Rows[i].Cells["MaMH"].Value.ToString();
                    int soluong = int.Parse(gv_ctbansi.Rows[i].Cells["SoLuong"].Value.ToString());
                    double dongia = double.Parse(gv_ctbansi.Rows[i].Cells["DonGia"].Value.ToString());
                    float chietkhau = float.Parse(gv_ctbansi.Rows[i].Cells["ChietKhau"].Value.ToString()) / 100;
                    double thanhtien = double.Parse(gv_ctbansi.Rows[i].Cells["ThanhTien"].Value.ToString());
                    if (!service.InsertCTHDBS(mamh, mahd, dongia, soluong, chietkhau, thanhtien))
                    {
                        MessageBox.Show("Lưu thất bại!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        if (ck_phieukhdathang.Checked == true)
                        {
                            //Cap Nhật lại Mặt hàng đã giao trong đơn đặt hàng NCC
                            service.selectqueryByText("update CTKHDatHang set DaGiao = 'true' where MaKHDH = '" + mcb_phieukhdathang.SelectedValue.ToString().Trim() + "' and MaMH = '" + mamh + "' ");

                        }
                    }
                }
                MessageBox.Show("Lưu hoá đơn thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //In phieu sau khi luu da dc Kich
                if (checkInSauKhiLuu.Checked == true)
                {
                    //In ra hoa don ban si
                    Report.frm_In_HDBS hdbs = new Report.frm_In_HDBS();
                    hdbs.mahdbs = mahd;
                    hdbs.ShowDialog();
                    //Xoa het cac thong tin
                    txttongthanhtien.Text = "0";
                    txttongthanhtientinhthue.Text = "0";
                    txtvat.Text = "0";
                    txtdathanhtoan.Text = "0";
                    txtconlai.Text = "0";
                    txttienthue.Text = "0";
                    txttienchu.Text = "Không đồng chẳn!";
                    if (ck_phieukhdathang.Checked == false)
                        gv_ctbansi.Rows.Clear();
                    txtsochungtu.Focus();
                }
                //xoa tat ca thong tin sau khi da luu hoa don va in phieu
                if (ck_phieukhdathang.Checked == true)
                {
                    Load_DSPhieuDatNCCChuaGiao();
                    gv_ctbansi.DataSource = null;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txtvat_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtvat.Text.Length!=0)
                {
                    txtvat.Text = int.Parse(txtvat.Text).ToString();
                    txttienthue.Text=(double.Parse(txttongthanhtien.Text)*double.Parse(txtvat.Text)/100).ToString("#,##0");
                    txttongthanhtientinhthue.Text = (double.Parse(txttongthanhtien.Text) + double.Parse(txttienthue.Text)).ToString("#,##0");
                    txtconlai.Text = (double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text)).ToString("#,##0");
                    txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
                }
                txtvat.SelectionStart = txtvat.Text.Length;
                //if (txtvat.Text != "0")
                //{
                //    double tienthueTam = tongtien / double.Parse(txtvat.Text);
                //    txttienthue.Text = tienthueTam.ToString("#,##0");

                //    txttongthanhtientinhthue.Text = (tongtien + tienthueTam).ToString("#,##0");
                //    txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
                //}
                //else if (txtvat.Text == "0")
                //{
                //    txttienthue.Text = double.Parse(txtvat.Text).ToString();
                //    double tongtam = double.Parse(txttongthanhtien.Text) - double.Parse(txtkhtamung.Text);
                //    txttongthanhtientinhthue.Text = tongtam.ToString("#,##0");
                //    txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));

                //}
                //else if (txtvat.Text == "")
                //{
                //    txtvat.Focus();
                //}
            }
            catch (Exception ex) { logger.Error("Error: " + ex.Message); }

        }

        private void txtsoluong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtsoluong.Text.Length != 0)
                {
                    txtsoluong.Text = double.Parse(txtsoluong.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txtsoluong.Text) * double.Parse(txtdongia.Text) - double.Parse(txtsoluong.Text) * double.Parse(txtdongia.Text) * float.Parse(txtkm.Text) / 100;
                    txtthanhtien.Text = thanhtien.ToString("#,##0");
                }
                txtsoluong.SelectionStart = txtsoluong.Text.Length;

            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txtdathanhtoan_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtdathanhtoan.Text.Length != 0)
                {
                    txtdathanhtoan.Text = double.Parse(txtdathanhtoan.Text).ToString("#,##0");
                    tienConLai = tongtien - double.Parse(txtdathanhtoan.Text);
                    txtconlai.Text = tienConLai.ToString("#,##0");

                    tienConLai = double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text) - double.Parse(txtkhtamung.Text);
                    txtconlai.Text = tienConLai.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txtdathanhtoan.SelectionStart = txtdathanhtoan.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txtdongia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtdongia.Text.Length != 0)
                {
                    txtdongia.Text = double.Parse(txtdongia.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txtsoluong.Text) * double.Parse(txtdongia.Text) - double.Parse(txtsoluong.Text) * double.Parse(txtdongia.Text) * float.Parse(txtkm.Text) / 100;
                    txtthanhtien.Text = thanhtien.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txtdongia.SelectionStart = txtdongia.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txttongthanhtien_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txttongthanhtien.Text.Trim() != "0")
                    txttongthanhtientinhthue.Text = (double.Parse(txttongthanhtien.Text) + double.Parse(txttienthue.Text)).ToString("#,##0");
            }
            catch (Exception) { }

            //if (txtvat.Text.Length != 0)
            //{
            //    if (txttongthanhtien.Text.Length != 0)
            //    {
            //        txttienthue.Text = (double.Parse(txttongthanhtien.Text) * double.Parse(txtvat.Text) / 100).ToString();
            //        txttongthanhtientinhthue.Text = (double.Parse(txttongthanhtien.Text) + double.Parse(txttienthue.Text)).ToString("#,##0");
            //        txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
            //        txtconlai.Text = (double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text)).ToString("#,##0");
            //    }
            //}
            //else
            //{
            //    txtvat.Text = "0";
            //    txttienthue.Text = "0";
            //    txttongthanhtientinhthue.Text = txttongthanhtien.Text;
            //    txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
            //    txtconlai.Text = (double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text)).ToString("#,##0");
            //}
            //if (txttongthanhtien.Text.Length != 0)
            //    txttongthanhtientinhthue.Text = (double.Parse(txttongthanhtien.Text) + double.Parse(txttienthue.Text)).ToString("#,##0"); ;
        }

        private void txttongthanhtientinhthue_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
            }
            catch (Exception) { }
        }

        private void btn_xemin_Click(object sender, EventArgs e)
        {
            //In ra Report
            try
            {
                DataSet ds = new DataSet();
                string mahdbs = "";
                ds.ReadXml(new StringReader(service.selectqueryByText("select top 1 MaHDBS from hoadonbansi order by MaHDBS desc")));
                if (ds.Tables.Count > 0)
                {
                    mahdbs = ds.Tables[0].Rows[0][0].ToString();
                    Report.frm_In_HDBS hdbs = new Report.frm_In_HDBS();
                    hdbs.mahdbs = mahdbs;
                    hdbs.ShowDialog();
                }

                //Xoa het cac thong tin
                txttongthanhtien.Text = "0";
                txttongthanhtientinhthue.Text = "0";
                txtvat.Text = "0";
                txtdathanhtoan.Text = "0";
                txtconlai.Text = "0";
                txttienthue.Text = "0";
                txttienchu.Text = "Không đồng chẳn!";
                if (ck_phieukhdathang.Checked == false)
                    gv_ctbansi.Rows.Clear();
                //xoa tat ca thong tin sau khi da luu hoa don va in phieu
                if (ck_phieukhdathang.Checked == true)
                {
                    Load_DSPhieuDatNCCChuaGiao();
                    gv_ctbansi.DataSource = null;
                }
            }
            catch (Exception ex)
            {
            }
        }

        #region Phuong thuc lien quan den chon Mat hang
        private void bt_chuyenxuong_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (txtmamh.Text == "")
            {
                errorProvider1.SetError(txtmamh, "Chưa chọn mặt hàng");
                cmbmahang.Focus();
                return;
            }
            if (ktmh(txtmamh.Text.Trim() + "") == false)
            {
                errorProvider1.SetError(txtmamh, "Mặt hàng không hợp lệ");
                cmbmahang.Focus();
                return;
            }
            if (txtsoluong.Text.Trim() == "" || double.Parse(txtsoluong.Text) == 0)
            {
                errorProvider1.SetError(txtsoluong, "Số lượng không hợp lệ");
                txtsoluong.Focus();
                return;
            }
            if (txtdongia.Text == "" || double.Parse(txtdongia.Text) == 0)
            {
                errorProvider1.SetError(txtdongia, "Đơn giá không hợp lệ");
                txtdongia.Focus();
                return;
            }
            try
            {
                if (gv_ctbansi.Rows.Count > 0)
                {
                    //Tang so luong va thay doi tong thanh tien + Truong hop gia tien khac nhau
                    for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                    {
                        if (cmbmahang.SelectedValue.ToString().Trim() == gv_ctbansi.Rows[i].Cells["mamh"].Value.ToString().Trim() && txtdongia.Text.Trim() == gv_ctbansi.Rows[i].Cells["DonGia"].Value.ToString().Trim())
                        {
                            gv_ctbansi.Rows[i].Cells["soluong"].Value = (int.Parse(gv_ctbansi.Rows[i].Cells["soluong"].Value.ToString()) + int.Parse(txtsoluong.Text.Trim())).ToString("#,##0");
                            gv_ctbansi.Rows[i].Cells["thanhtien"].Value = (int.Parse(gv_ctbansi.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_ctbansi.Rows[i].Cells["dongia"].Value.ToString()) - int.Parse(gv_ctbansi.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_ctbansi.Rows[i].Cells["dongia"].Value.ToString()) * double.Parse(gv_ctbansi.Rows[i].Cells["chietkhau"].Value.ToString()) / 100).ToString("#,##0");
                            //Tinh tong tien hang
                            tongtienhang = 0;
                            for (int j = 0; j < gv_ctbansi.Rows.Count; j++)
                            {
                                tongtienhang += double.Parse(gv_ctbansi.Rows[j].Cells["ThanhTien"].Value.ToString());
                            }
                            txttongthanhtien.Text = tongtienhang.ToString("#,##0");
                            cmbmahang.Focus();
                            return;
                        }
                    }
                }
                //Gan gia tri cho bien
                mamh = txtmamh.Text;
                tenmh = cmbmahang.Text.Trim();
                soluong = txtsoluong.Text;
                dongia = txtdongia.Text;
                chietkhau = float.Parse(txtkm.Text);
                thanhtien = txtthanhtien.Text;
                if (gv_ctbansi.Rows.Count != 0)
                    vitri = gv_ctbansi.Rows.Count;
                else
                    vitri = 0;                
                //them mat hang xuong girdview                
                gv_ctbansi.Rows.AddNew();
                gv_ctbansi.Rows[vitri].Cells["MaMH"].Value = mamh;
                gv_ctbansi.Rows[vitri].Cells["TenMH"].Value = tenmh;
                gv_ctbansi.Rows[vitri].Cells["SoLuong"].Value = soluong;
                gv_ctbansi.Rows[vitri].Cells["DonGia"].Value = dongia;
                gv_ctbansi.Rows[vitri].Cells["ChietKhau"].Value = chietkhau;
                gv_ctbansi.Rows[vitri].Cells["ThanhTien"].Value = thanhtien;                
                //Thêm nút xóa trong GridView          
                if (gv_ctbansi.Columns.GetColumnByFieldName("xoa").Length == 0)
                {
                    GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                    btnColumn.FieldName = "xoa";
                    btnColumn.Name = "xoa";
                    btnColumn.UseDefaultText = true;
                    btnColumn.DefaultText = "Xóa";
                    gv_ctbansi.Columns.Insert(gv_ctbansi.Columns.Count, btnColumn);
                }
                //Tao STT cho GridView
                if (txtvat.Text.Length != 0)
                {
                    tongtienhang = 0;
                    tongtien = 0;
                    for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                    {
                        gv_ctbansi.Rows[i].Cells["STT"].Value = i + 1;
                        //Tinh Tong Tien
                        tongtienhang += double.Parse(gv_ctbansi.Rows[i].Cells["ThanhTien"].Value.ToString());
                    }
                    txttongthanhtien.Text = tongtienhang.ToString("#,##0");
                    tongtien = tongtienhang + double.Parse(txttienthue.Text);
                    txttongthanhtientinhthue.Text = tongtien.ToString("#,##0");
                    txttienchu.Text = So_chu(tongtien);
                    if (txtdathanhtoan.Text.Length != 0)
                    {
                        txtconlai.Text = (double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text)).ToString("#,##0");
                    }
                }
                //Xoa bo thong tin trong cac o mat hang
                txtmamh.Text = "";
                cmbmahang.SelectedIndex = -1;
                txtsoluong.Text = "1";
                txtdongia.Text = "0";
                cmbdvt.Text = "";
                txtthanhtien.Text = "0";
                txtkm.Text = "0";
                cmbmahang.Focus();
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        #endregion

        #region Cac phuong thuc su ly
        private string xulyma()
        {
            DataSet ds_tam = new DataSet();
            string mamoi = "";
            try
            {
                string chuoi = "BS" + DateTime.Today.Year.ToString("0000") + DateTime.Today.Month.ToString("00");
                ds_tam.ReadXml(new StringReader(service.selectqueryByText("select top 1 mahdbs from hoadonbansi where mahdbs like '%" + chuoi + "%'order by mahdbs desc")));
                if (ds_tam.Tables.Count == 0)
                    mamoi = chuoi + "0001";
                else
                {
                    string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                    string kituso = matam.Substring(8, 4).ToString();
                    int somoi = int.Parse(kituso) + 1;
                    mamoi = chuoi + somoi.ToString("0000");
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
            return mamoi;
        }
        #endregion

        #region Các hàm Load
        //ArrayList test_DSMH;
        private void LoadDuLieu()
        {
            try
            {
                //Chỉnh độ dài của các cột trong multcombobox
                RadMultiColumnComboBoxElement multicbb_kho = this.cmbkhohang.MultiColumnComboBoxElement;
                RadMultiColumnComboBoxElement multicbb_khachhang = this.cmbkhachhang.MultiColumnComboBoxElement;
                RadMultiColumnComboBoxElement multicbb_mathang = this.cmbmahang.MultiColumnComboBoxElement;
                multicbb_kho.AutoCompleteMode = AutoCompleteMode.None;
                multicbb_kho.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multicbb_khachhang.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multicbb_mathang.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multicbb_kho.DropDownMinSize = new Size(300, 300);
                multicbb_khachhang.DropDownMinSize = new Size(500, 200);
                multicbb_mathang.DropDownMinSize = new Size(600, 200);
                //Load mat hang
                DataSet ds2 = new DataSet();
                ds2.ReadXml(new StringReader(service.selectqueryByText("select MaMH,TenMH,DonGiaSi,DVT,KhuyenMai from MatHang")));
                if (ds2.Tables.Count > 0)
                {
                    cmbmahang.DataSource = ds2.Tables[0];
                    cmbmahang.DisplayMember = "TenMH";
                    cmbmahang.ValueMember = "MaMH";
                    cmbmahang.SelectedIndex = -1;
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.cmbmahang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                cmbmahang.EditorControl.FilterDescriptors.Add(des_mh);
                //Load khach hang
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(service.LayDS_KhachHang()));
                if (ds.Tables.Count > 0)
                {
                    Test_DMKH = new ArrayList();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
			        {
                        Test_DMKH.Add(ds.Tables[0].Rows[i]["HoTenKh"].ToString().Trim());
			        }
                    
                    cmbkhachhang.DataSource = ds.Tables[0];
                    cmbkhachhang.DisplayMember = "HoTenKH";
                    cmbkhachhang.ValueMember = "MaKH";
                    cmbkhachhang.SelectedIndex = -1;

                }
                FilterDescriptor des_kh = new FilterDescriptor(this.cmbkhachhang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                cmbkhachhang.EditorControl.FilterDescriptors.Add(des_kh);
                //Load kho hang
                DataSet ds1 = new DataSet();
                ds1.ReadXml(new StringReader(service.selectqueryByText("select makho,tenkho from kho")));
                if (ds1.Tables.Count > 0)
                {
                    Test_DMKho = new ArrayList();
                    for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                    {
                        Test_DMKho.Add(ds1.Tables[0].Rows[i]["TenKho"].ToString().Trim());
                    }
                    cmbkhohang.DataSource = ds1.Tables[0];
                    cmbkhohang.DisplayMember = "tenkho";
                    cmbkhohang.ValueMember = "makho";
                    cmbkhohang.SelectedIndex = -1;
                }
                FilterDescriptor des_kho = new FilterDescriptor(this.cmbkhohang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                cmbkhohang.EditorControl.FilterDescriptors.Add(des_kho);

            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        private void Load_DSPhieuDatNCCChuaGiao()
        {
            try
            {
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcb_phieukhdathang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                string sql = "Select hd.MaKHDH,NgayThangDH,MaKho,MaKH,GhiChuDH, TamUng "
                             + "from PhieuKHDatHang hd,CTKHDatHang ct "
                             + "where hd.MaKHDH = ct.MaKHDH and  DaGiao = 'false' "
                             + "group by hd.MaKHDH,NgayThangDH,MaKho,MaKH,GhiChuDH,TamUng";
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(service.selectqueryByText(sql)));
                if (ds.Tables.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        ds.Tables[0].Rows[i]["NgayThangDH"] = DateTime.Parse(ds.Tables[0].Rows[i]["NgayThangDH"].ToString()).ToShortDateString();
                    }
                    mcb_phieukhdathang.DataSource = ds.Tables[0];
                    mcb_phieukhdathang.DisplayMember = "MaKHDH";
                    mcb_phieukhdathang.ValueMember = "MaKHDH";
                    mcb_phieukhdathang.SelectedIndex = -1;
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.mcb_phieukhdathang.ValueMember, FilterOperator.StartsWith, string.Empty);
                mcb_phieukhdathang.EditorControl.FilterDescriptors.Add(des_mh);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        private bool ktmh(string mamh)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select mamh from mathang where mamh like'" + mamh.Trim() + "'")));
            if (ds.Tables.Count > 0)
            {
                return true;
            }
            return false;
        }
        private void KhoaConTrol(bool khoa)
        {
            cmbkhachhang.Enabled = khoa;
            cmbmahang.Enabled = khoa;
            cmbkhohang.Enabled = khoa;
            txtsoluong.Enabled = khoa;
            txtdongia.Enabled = khoa;
            txtkm.Enabled = khoa;
            txtthanhtien.Enabled = khoa;
            bt_chuyenxuong.Enabled = khoa;
            cmbdvt.Enabled = khoa;
        }
        #endregion

        #region Bilding dữ liệu khi chọn phiếu đặt hàng NCC
        private void ck_phieukhdathang_CheckedChanged(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (ck_phieukhdathang.Checked == true)
            {
                //giaodien
                mcb_phieukhdathang.Enabled = true;
                gv_ctbansi.Columns["soluong"].ReadOnly = true;
                gv_ctbansi.Columns["dongia"].ReadOnly = true;
                gv_ctbansi.Columns["chietkhau"].ReadOnly = true;
                txtkhtamung.Enabled = true;
                KhoaConTrol(false);

            }
            else if (ck_phieukhdathang.Checked == false)
            {
                //giaodien
                gv_ctbansi.Columns["soluong"].ReadOnly = false;
                gv_ctbansi.Columns["dongia"].ReadOnly = false;
                gv_ctbansi.Columns["chietkhau"].ReadOnly = false;
                txtkhtamung.Enabled = false;
                mcb_phieukhdathang.Enabled = false;
                mcb_phieukhdathang.Text = "";
                gv_ctbansi.DataSource = null;
                KhoaConTrol(true);
                txttongthanhtien.Text = "0";
                txtdiachi.Text = "";
                txtkhtamung.Text = "0";
                cmbkhohang.Text = "";
                cmbkhachhang.Text = "";
                txtdathanhtoan.Text = "0";
                txtconlai.Text = "0";
                //pannel_mathang.Enabled = true;
                txtvat.Text = "0";
                txttienthue.Text = "0";
                txttongthanhtientinhthue.Text = "0";
                txttienchu.Text = "Không đồng chắn.";
            }
        }
        #endregion

        #region Khi thay đổi số lượng trong gridview
        private void gv_ctbansi_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            errorProvider1.Clear();
            try
            {
                if (Regex.IsMatch(gv_ctbansi.CurrentRow.Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_ctbansi.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                {
                    lbl_Thongbao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_Thongbao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_ctbansi.CurrentRow.Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,12}$") == false)
                {
                    lbl_Thongbao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_Thongbao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_ctbansi.CurrentRow.Cells["Chietkhau"].Value.ToString().Trim(), @"^(\d{1,2})$") == false || int.Parse(gv_ctbansi.CurrentRow.Cells["ChietKhau"].Value.ToString()) > 50)
                {
                    lbl_Thongbao.Text = "Số chiết khấu từ 0 - 50 %";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_Thongbao, "Xem lại thông tin trên lưới.");
                    return;
                }
                lbl_Thongbao.Text = "Thông báo!";
                errorProvider1.RightToLeft = true;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        private void gv_ctbansi_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            try
            {
                double tongtien_sausua = 0;
                double dongia = double.Parse(gv_ctbansi.CurrentRow.Cells["DonGia"].Value.ToString());
                int soluong = int.Parse(gv_ctbansi.CurrentRow.Cells["Soluong"].Value.ToString().Trim());
                float khuyenmai = float.Parse(gv_ctbansi.CurrentRow.Cells["ChietKhau"].Value.ToString());
                double thanhtien = (soluong * dongia) - ((soluong * dongia) * khuyenmai) / 100;
                gv_ctbansi.CurrentRow.Cells["ThanhTien"].Value = thanhtien.ToString("#,##0");

                for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                {
                    gv_ctbansi.Rows[i].Cells["SoLuong"].Value = double.Parse(gv_ctbansi.Rows[i].Cells["SoLuong"].Value.ToString()).ToString("#,##0");
                    gv_ctbansi.Rows[i].Cells["DonGia"].Value = double.Parse(gv_ctbansi.Rows[i].Cells["DonGia"].Value.ToString()).ToString("#,##0");
                    tongtien_sausua += double.Parse(gv_ctbansi.Rows[i].Cells["ThanhTien"].Value.ToString());
                }
                txttongthanhtien.Text = tongtien_sausua.ToString("#,##0");
                txtdathanhtoan.Text = "0";
            }
            catch
            {
            }
        }
        #endregion  

        private void txtdathanhtoan_Leave(object sender, EventArgs e)
        {
            try
            {
                if (txtdathanhtoan.Text.Length != 0)
                {
                    double tientamungTam = double.Parse(txtdathanhtoan.Text);
                    txtdathanhtoan.Text = tientamungTam.ToString("#,##0");

                    tienDaDua = tientamungTam;

                    tienConLai = double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text);
                    txtconlai.Text = tienConLai.ToString("#,##0");
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txtkm_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtkm.Text.Trim() != "")
                {
                    if (int.Parse(txtkm.Text) != 0)
                    {
                        double thanhtien = double.Parse(txtsoluong.Text) * double.Parse(txtdongia.Text) - double.Parse(txtsoluong.Text) * double.Parse(txtdongia.Text) * float.Parse(txtkm.Text) / 100;
                        txtthanhtien.Text = thanhtien.ToString("#,##0");
                    }
                    else
                    {
                        txtthanhtien.Text = (int.Parse(txtdongia.Text) * int.Parse(txtsoluong.Text)).ToString("#,##0");
                    }
                }
            }
            catch
            {
            }
        }

        private void radButton52_Click(object sender, EventArgs e)
        {
            frmBC_ChiTietBanHang hdbs = new frmBC_ChiTietBanHang();
            hdbs.Show();
        }        

        private void txtkhtamung_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tamung = double.Parse(mcb_phieukhdathang.EditorControl.Rows[mcb_phieukhdathang.SelectedIndex].Cells["TamUng"].Value.ToString()).ToString("#,##0");
                if (txtkhtamung.Text == tamung || txtkhtamung.Text == "0")
                {

                    tongtien = double.Parse(txttongthanhtien.Text) + double.Parse(txttienthue.Text) - double.Parse(txtkhtamung.Text);
                    txttongthanhtientinhthue.Text = tongtien.ToString("#,##0");
                }
                else
                {
                    txtkhtamung.Focus();
                    return;
                }
            }
            catch
            {
            }
        }

        private void dtpngaylaphd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData== Keys.Enter)
            {
                txtsochungtu.Focus();
                txtsochungtu.SelectionStart = txtsochungtu.Text.Length;
            }
        }

        private void txtsochungtu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                cmbkhohang.Focus();
            }
        }

        private void cmbkhohang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                cmbkhachhang.Focus();
            }
        }

        private void gv_ctbansi_CommandCellClick(object sender, EventArgs e)
        {
            double tongtien_sauxoa = 0;
            try
            {
                if (MessageBox.Show("Bạn muốn xóa chi tiết này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (gv_ctbansi.Rows.Count == 1)
                    {
                        gv_ctbansi.Rows.Clear();
                    }
                    else
                    {
                        gv_ctbansi.Rows.RemoveAt(gv_ctbansi.CurrentRow.Index);
                        for (int i = 0; i < gv_ctbansi.Rows.Count; i++)
                        {
                            gv_ctbansi.Rows[i].Cells["STT"].Value = i + 1;
                        }
                    }
                    for (int j = 0; j < gv_ctbansi.Rows.Count; j++)
                    {
                        tongtien_sauxoa += double.Parse(gv_ctbansi.Rows[j].Cells["ThanhTien"].Value.ToString());
                    }
                    txttongthanhtien.Text = tongtien_sauxoa.ToString("#,##0");
                    if (txtvat.Text.Length != 0)
                    {
                        if (txttongthanhtien.Text.Length != 0)
                        {
                            tienthue = double.Parse(txttongthanhtien.Text) * double.Parse(txtvat.Text) / 100;
                            txttienthue.Text = tienthue.ToString("#,##0");
                            txttongthanhtientinhthue.Text = (double.Parse(txttongthanhtien.Text) + tienthue - double.Parse(txtkhtamung.Text)).ToString("#,##0");
                            txttienchu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
                            if (txtdathanhtoan.Text.Length!=0)
                            {
                                txtconlai.Text = (double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text)).ToString("#,##0");
                            }
                        }
                    }
                    else
                    {
                        txtvat.Text = "0";
                        txttongthanhtientinhthue.Text = txttongthanhtien.Text;
                        txtghichu.Text = So_chu(double.Parse(txttongthanhtientinhthue.Text));
                        if (txtdathanhtoan.Text.Length != 0)
                        {
                            txtconlai.Text = (double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtdathanhtoan.Text)).ToString("#,##0");
                        }
                    }
                    
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }


        }

        private void radButton48_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
